<template>
  <div class="app-container">
    <el-card>
      <h4>收到投递</h4>
      <el-row
        :gutter="10"
        style="background-color: rgb(249, 249, 249); padding: 18px 0px"
      >
        <el-col :span="13">
          <el-form ref="form" :model="form" label-width="80px">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="应聘职位:">
                  <el-select
                    v-model="receiveJLQuery.jobid"
                    placeholder=""
                    clearable
                    @change="positionListChange"
                  >
                    <el-option
                      v-for="item in releaseList"
                      :key="item.id"
                      :label="item.jobname"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="处理状态:">
                  <el-select
                    clearable
                    v-model="receiveJLQuery.status"
                    placeholder=""
                    @change="statusChange"
                  >
                    <el-option
                      v-for="item in handleStatus"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="查看状态:">
                  <el-select
                    clearable
                    v-model="receiveJLQuery.isLook"
                    placeholder=""
                    @change="viewStatusChange"
                  >
                    <el-option
                      v-for="item in viewStatus"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="简历来源:">
                  <el-select
                    clearable
                    v-model="receiveJLQuery.source"
                    placeholder=""
                    @change="resumeSourceChange"
                  >
                    <el-option
                      v-for="item in resumeSource"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="11">
          <div class="resume_list">
            <div class="resume_handle">
              <span class="bar"></span>
              近两周简历处理情况
            </div>
          </div>
          <div class="resume_header_font">
            收到简历：
            <span class="number">{{ handleList.count }}</span>
            待查看简历：
            <span class="number">{{ handleList.noLookCount }}</span>
            查看率：
            <span class="number">{{ handleList.percent }}</span>
          </div>
        </el-col>
      </el-row>
      <el-table :data="receiveJLList" style="width: 100%">
        <el-table-column prop="prop" label="基本信息" width="260">
          <template slot-scope="scope">
            <div style="display: flex">
              <div class="portraitImg">
                <img
                  style="width: 52px; height: 52px"
                  :src="
                    scope.row.photoImg === 0
                      ? scope.row.photoImgSrc
                      : 'https://blwcompany.nbblmc.cn' + scope.row.photoImgSrc
                  "
                  alt=""
                />
              </div>
              <div>
                <div style="text-align: left">
                  <span>{{ scope.row.fullname }}</span>
                  <span
                    class="no_look"
                    v-if="scope.row.handleStatus === 0"
                  ></span>
                </div>
                <p>
                  {{ scope.row.age }}岁 | {{ scope.row.educationText }} |
                  {{ scope.row.experienceText }}经验 | {{ scope.row.sexText }}
                </p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="jobname"
          label="应聘职位"
          width="width"
          align="center"
        >
          <!-- <template slot-scope="scope">
            <el-link :href="scope.row.jobLinkUrlWeb" type="primary">{{
              scope.row.jobname
            }}</el-link>
          </template> -->
        </el-table-column>
        <el-table-column
          prop="prop"
          label="求职意向"
          width="width"
          align="center"
        >
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.intentionJobs"
              placement="top"
              :hide-after="0"
            >
              <div class="ellipsis">
                想找
                <span style="color: #409eff">{{
                  scope.row.intentionJobs
                }}</span>
                工作
              </div>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              :content="scope.row.intentionDistrict"
              placement="bottom"
              :hide-after="0"
            >
              <div class="ellipsis">
                想在
                <span style="color: #409eff">{{
                  scope.row.intentionDistrict
                }}</span>
                工作
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="prop"
          label="应聘时间"
          width="width"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.addtime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getTagType(scope.row.handleStatus)">{{
              getStatusText(scope.row.handleStatus)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="prop" label="操作" width="400" align="center">
          <template slot-scope="scope">
            <div style="display: flex; justify-content: center; gap: 2px">
              <div style="width: 70px; text-align: right">
                <el-button
                  type="primary"
                  size="mini"
                  v-if="scope.row.handleStatus === 0"
                  @click="interviewYqClick(scope.row)"
                  >同意</el-button
                >
              </div>
              <div style="width: 65px; text-align: right">
                <el-button
                  type="danger"
                  size="mini"
                  v-if="scope.row.handleStatus === 0"
                  @click="refuseClick(scope.row.id)"
                  >婉拒</el-button
                >
              </div>
              <div style="width: 65px; text-align: right">
                <el-button
                  type="primary"
                  size="mini"
                  @click="notesClick(scope.row)"
                  >备注</el-button
                >
              </div>
              <div style="width: 65px; text-align: right">
                <el-button size="mini" @click="delClick(scope.row.id)"
                  >删除</el-button
                >
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-row :gutter="10" style="margin-top: 20px" type="flex" justify="end">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-row>
      <!-- 备注弹框 -->
      <el-dialog
        title="填写备注"
        :visible.sync="notesVisible"
        width="500px"
        custom-class="self-dialog"
      >
        <div class="candidate-info">
          <div class="info-row">简历姓名： {{ notesForm.fullname }}</div>
          <div class="info-row">
            基本信息：{{ notesForm.age }} | {{ notesForm.sexText }} |
            {{ notesForm.educationText }} | {{ notesForm.experienceText }}经验
          </div>
        </div>

        <div class="remark-form">
          <div class="form-label">备注：</div>
          <el-input
            v-model="notesForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入备注内容"
            :maxlength="50"
            show-word-limit
          >
          </el-input>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="notesVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRemark">确定</el-button>
        </div>
      </el-dialog>
      <!-- 面试邀请 -->
      <el-dialog
        title="面试邀请"
        :visible.sync="interviewYqVisible"
        width="500px"
        custom-class="interview-dialog"
      >
        <el-form
          :model="InterrviewForm"
          :rules="rules"
          ref="interviewForm"
          label-width="80px"
          class="interview-form"
        >
          <!-- 面试形式 -->
          <el-form-item label="面试形式">
            <el-radio-group v-model="InterrviewForm.type">
              <el-radio :label="1">面试邀请</el-radio>
              <el-radio :label="2" disabled>视频面试</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 面试人 -->
          <el-form-item label="面试人" prop="fullname">
            <span class="candidate-name">{{ fullName }}</span>
          </el-form-item>

          <!-- 面试职位 -->
          <el-form-item label="面试职位" prop="jobid">
            <el-select v-model="InterrviewForm.jobid" placeholder="请选择职位">
              <el-option
                v-for="item in positionLists"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 面试日期 -->
          <el-form-item label="面试日期" prop="interviewDate">
            <el-date-picker
              v-model="InterrviewForm.interviewDate"
              @change="handleDateChange"
              type="date"
              placeholder="请选择面试日期"
            >
            </el-date-picker>
          </el-form-item>

          <!-- 面试时间 -->
          <el-form-item label="面试时间" prop="interviewTime">
            <el-time-select
              v-model="InterrviewForm.interviewTime"
              @change="handleInterviewTime"
              :picker-options="{
                start: '08:00',
                step: '00:10',
                end: '20:00',
              }"
              placeholder="选择时间"
            >
            </el-time-select>
          </el-form-item>

          <!-- 面试地点 -->
          <el-form-item label="面试地点" prop="address">
            <el-input
              v-model="InterrviewForm.address"
              placeholder="请输入面试地点"
            ></el-input>
          </el-form-item>

          <!-- 联系人 -->
          <el-form-item label="联系人" prop="contact">
            <el-input
              v-model="InterrviewForm.contact"
              placeholder="请输入联系人"
            ></el-input>
          </el-form-item>

          <!-- 联系电话 -->
          <el-form-item label="联系电话" prop="tel">
            <el-input
              v-model="InterrviewForm.tel"
              placeholder="请输入联系电话"
            ></el-input>
          </el-form-item>

          <!-- 备注 -->
          <el-form-item label="备注" prop="note">
            <el-input
              v-model="InterrviewForm.note"
              type="textarea"
              :rows="3"
              placeholder="请填写备注"
            >
            </el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="interviewYqVisible = false">取消</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  receivedResumeListApi,
  latelyTwoWeeksApi,
  delDeliveryApi,
  updateDeliveryStatusApi,
  selRemarkByCidAndRidApi,
  addRemarkApi,
  updateRemarksApi,
  addInterviewApi,
  selCompanyContentListApi,
} from "@/api/jlManage";
import { positionListApi } from "@/api/position";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      // 收到投递请求参数
      receiveJLQuery: {
        uid: "",
        page: 1,
        pageSize: 10,
        isLook: null,
        jobid: null,
        source: null,
        status: null,
      },
      receiveJLList: [],
      handleList: {},
      // 新增备注
      notesForm: {
        id: null,
        comid: "",
        resumeId: "",
        remark: "",
        age: "",
        educationText: "",
        experienceText: "",
        fullname: "",
        sexText: "",
      },
      total: 0,
      // 处理状态
      handleStatus: [
        { value: "", label: "全部" },
        { value: 0, label: "待处理" },
        { value: 1, label: "已同意" },
        { value: 2, label: "已拒绝" },
      ],
      // 查看状态
      viewStatus: [
        { value: "", label: "全部" },
        { value: 0, label: "未查看" },
        { value: 1, label: "已查看" },
      ],
      // 简历来源
      resumeSource: [
        { value: "", label: "全部" },
        { value: 0, label: "自主投递" },
        { value: 1, label: "委托投递" },
      ],
      // 职位列表请求参数
      positionQuery: {
        audit: 1,
        page1: 1,
        pageSize: 10,
        uid: "",
      },
      // 修改投递状态
      editStatus: {
        id: "",
        status: 2,
      },
      // 职位列表
      positionLists: [],
      // 新增备注
      notesForm: {
        id: null,
        comid: "",
        resumeId: "",
        remark: "",
        age: "",
        educationText: "",
        experienceText: "",
        fullname: "",
        sexText: "",
      },
      fullName: "",
      // 新增备注表单提交
      notesFormSubmit: {},
      notesVisible: false,
      interviewYqVisible: false,
      // 面试邀请表单
      InterrviewForm: {
        id: "",
        address: "",
        contact: "",
        interviewDate: "",
        interviewTime: "",
        jobid: null,
        resumeId: null,
        tel: "",
        type: 1,
        note: "",
      },
      // 职位列表
      jobList: [],
      rules: {
        contact: [{ required: true, message: "请输入联系人", trigger: "blur" }],
        interviewDate: [
          { required: true, message: "请选择面试日期", trigger: "change" },
        ],
        interviewTime: [
          { required: true, message: "请选择面试时间", trigger: "change" },
        ],
        tel: [
          {
            required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确的电话号码",
            trigger: "blur",
          },
        ],
        jobid: [{ required: true }],
        resumeId: [{ required: true }],
        type: [{ required: true }],
      },
      releaseList: [],
    };
  },
  computed: {
    ...mapGetters(["userId", "cid"]),
  },
  created() {
    this.receiveJLQuery.uid = this.userId;
    this.positionQuery.uid = this.userId;
    this.receivedResumeList();
    this.latelyTwoWeeks();
    this.positionList();
  },
  methods: {
    // 点击备注
    async notesClick(row) {
      console.log(row);
      const res = await selRemarkByCidAndRidApi({
        cid: this.cid,
        rid: row.resumeId,
      });
      console.log(res);
      if (res.data) {
        this.$set(row, "remark", res.data.remark);
        this.$set(row, "id", res.data.id);
      }
      this.notesForm = row;
      console.log(this.notesForm);
      this.notesVisible = true;
    },
    // 点击确定
    async submitRemark() {
      try {
        // 使用 id 是否存在来判断是新增还是更新
        if (this.notesForm.remark) {
          const res = await updateRemarksApi({
            id: this.notesForm.id,
            remark: this.notesForm.remark || "", // 确保 remark 不为 undefined
          });
          if (res.code === 1) {
            this.$message.success("修改备注成功!");
            this.notesVisible = false;
          } else {
            this.$message.error("修改备注失败");
          }
        } else {
          const res = await addRemarkApi({
            comid: this.cid,
            resumeId: this.notesForm.resumeId,
            remark: this.notesForm.remark || "", // 确保 remark 不为 undefined
          });
          if (res.code === 1) {
            this.$message.success("新增备注成功!");
            this.notesVisible = false;
          } else {
            this.$message.error("新增备注失败");
          }
        }
      } catch {
        this.$message.error("备注失败");
      }
    },
    // 职位列表下拉改变
    positionListChange(val) {
      console.log(val);
      this.receivedResumeList();
    },
    // 处理状态下拉改变
    statusChange(val) {
      console.log(val);
      this.receivedResumeList();
    },
    // 查看状态下拉改变
    viewStatusChange(val) {
      console.log(val);
      this.receivedResumeList();
    },
    // 简历来源下拉改变
    resumeSourceChange(val) {
      console.log(val);
      this.receivedResumeList();
    },
    // 职位列表
    async positionList() {
      const res = await positionListApi(this.positionQuery);
      console.log(res);
      this.positionLists = res.records.map((item) => {
        return {
          value: item.id,
          name: item.jobname,
        };
      });
      // 添加"全部"选项
      this.releaseList = [{ id: "", jobname: "全部" }, ...res.records];
    },
    // 分页选择页数改变
    handleSizeChange(val) {
      // 更新分页大小为传入的值
      this.receiveJLQuery.pageSize = val;
      this.receivedResumeList();
    },
    // 分页选择页码改变
    handleCurrentChange(val) {
      this.receiveJLQuery.page = val;
      this.receivedResumeList();
    },
    // 删除投递记录
    async delClick(id) {
      try {
        console.log(id);
        this.$confirm("确定删除该简历吗？", "系统提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const res = await delDeliveryApi(id);
            if (res.code === 1) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.receivedResumeList();
            } else {
              this.$message.error("删除失败");
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } catch {
        this.$message.error("删除失败");
      }
    },
    // 婉拒
    refuseClick(id) {
      console.log(id);
      this.$confirm("确定要处理状态更改为【已婉拒】吗？", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.$loading({
            lock: true,
            text: "正在处理...",
            spinner: "el-icon-loading",
          });
          this.editStatus.id = id;
          try {
            const res = await updateDeliveryStatusApi(this.editStatus);
            if (res.code === 1) {
              this.$message.success("婉拒成功!");
              this.receivedResumeList();
              this.latelyTwoWeeks();
            } else {
              this.$message.error("婉拒失败!");
            }
          } catch (error) {
            console.error("婉拒失败:", error);
            this.$message.error("婉拒失败!");
          } finally {
            this.$loading().close();
          }
        })
        .catch(() => {
          // 用户点击取消，不需要处理
        });
    },
    // 收到列表查询
    async receivedResumeList() {
      const res = await receivedResumeListApi(this.receiveJLQuery);
      this.receiveJLList = res.records;
      this.total = res.total;
    },
    // 近两周简历处理情况
    async latelyTwoWeeks() {
      const res = await latelyTwoWeeksApi(this.userId);
      this.handleList = res.data;
    },
    getTagType(status) {
      switch (status) {
        case 0:
          return "warning"; // 待处理
        case 1:
          return "success"; // 已同意
        case 2:
          return "danger"; // 已婉拒
        default:
          return "info";
      }
    },
    getStatusText(status) {
      switch (status) {
        case 0:
          return "待处理";
        case 1:
          return "已同意";
        case 2:
          return "已婉拒";
        default:
          return "未知状态";
      }
    },
    // 面试邀请
    async interviewYqClick(row) {
      console.log(row);
      this.fullName = row.fullname;
      this.interviewYqVisible = true;
      this.InterrviewForm.resumeId = row.resumeId;
      this.InterrviewForm.id = row.id;
      // 获取企业联系人信息
      await this.selCompanyContentList();
    },
    // 面试时间状态改变
    handleInterviewTime(value) {
      if (value) {
        this.InterrviewForm.interviewTime = value;
      }
    },
    // 面试日期状态改变
    handleDateChange(value) {
      if (value) {
        this.InterrviewForm.interviewDate = value;
      }
    },
    // 提交面试邀请
    submitForm() {
      this.$refs.interviewForm.validate(async (valid) => {
        if (valid) {
          this.$loading({
            lock: true,
            text: "正在发送面试邀请...",
            spinner: "el-icon-loading",
          });
          try {
            // 获取面试日期的时间戳（秒级）
            const interviewDate = new Date(this.InterrviewForm.interviewDate);
            interviewDate.setHours(0, 0, 0, 0);
            const dateTimestamp = Math.floor(interviewDate.getTime() / 1000);

            // 将选择的时间转换为秒数
            const [hours, minutes] =
              this.InterrviewForm.interviewTime.split(":");
            const timeSeconds = parseInt(hours) * 3600 + parseInt(minutes) * 60;

            // 创建要提交的数据
            const submitData = {
              ...this.InterrviewForm,
              interviewDate: dateTimestamp,
              interviewTime: dateTimestamp + timeSeconds,
            };

            const res = await addInterviewApi(submitData);
            if (res.code === 1) {
              // 更新投递状态为已同意
              await this.updateDeliveryStatus(this.InterrviewForm.id);
              this.$message.success("面试邀请发送成功");
              this.closeInterviewDialog();
            } else {
              this.$message.error("面试邀请发送失败");
            }
          } catch (error) {
            console.error("面试邀请发送失败:", error);
            this.$message.error("面试邀请发送失败");
          } finally {
            this.$loading().close();
          }
        }
      });
    },
    // 关闭面试邀请弹窗
    closeInterviewDialog() {
      this.interviewYqVisible = false;
      this.$refs.interviewForm.resetFields();
      this.InterrviewForm.type = 1; // 重置为默认值
    },
    // 更新投递状态为已同意
    async updateDeliveryStatus(resumeId) {
      try {
        const res = await updateDeliveryStatusApi({
          id: resumeId,
          status: 1, // 1表示已同意
        });
        if (res.code === 1) {
          this.receivedResumeList(); // 刷新列表
          this.latelyTwoWeeks(); // 刷新处理情况统计
        }
      } catch (error) {
        console.error("更新投递状态失败:", error);
        throw error; // 向上抛出错误，让调用方知道更新失败
      }
    },
    // 查询企业联系人列表
    async selCompanyContentList() {
      const res = await selCompanyContentListApi(this.userId);
      if (res.data) {
        this.InterrviewForm.tel = res.data.companyMobile;
        this.InterrviewForm.contact = res.data.companyContent;
        this.InterrviewForm.address = res.data.companyAddress;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.portraitImg {
  // display: flex;
  flex: 1;
  margin-right: 10px;
  border-radius: 50%;
}
.resume_handle {
  line-height: 20px;
  margin-bottom: 10px;
  padding: 15px 0px;
  color: rgb(51, 51, 51);
  font-size: 14px;
}
.bar {
  width: 4px;
  height: 16px;
  background: rgb(23, 135, 251);
  display: inline-block;
  margin: -3px 5px -3px 0px;
}
.number {
  color: rgb(74, 136, 247);
  font-size: 22px;
  margin-right: 65px;
}
.substring {
  display: inline-block;
  max-width: 71%;
  color: black;
  margin: 0 5px;
}
.no_look {
  display: inline-block; /* 改为内联块级元素 */
  margin-left: 10px;
  width: 33px;
  height: 20px;
  background: url()
    0 no-repeat;
  vertical-align: middle; /* 垂直居中对齐 */
}
.self-dialog {
  .el-dialog__header {
    background: #f3f3f3;
    text-align: center;
    font-size: 15px;
    color: #333;
  }
}

.info-row {
  margin-bottom: 24px;
  margin-left: 24px;
  font-size: 14px;
}

.remark-form {
  display: flex;
}

.form-label {
  width: 50px;
  margin-left: 24px;
}
</style>
